//
//  DspLoginVC.m
//  WuyouTang
//
//  Created by YunBao on 2018/6/8.
//  Copyright © 2018年 cat. All rights reserved.
//

#import "DspLoginVC.h"

/******shark sdk *********/
#import <ShareSDK/ShareSDK.h>
#import <ShareSDKConnector/ShareSDKConnector.h>
#import "JPUSHService.h"
#import "AppDelegate.h"
#import "AFNetworking.h"
#import "YBTabBarController.h"
#import "PubH5.h"
#import "YBLookVideoVC.h"
#import "RegAlertView.h"
#import "CountryCodeVC.h"

@interface DspLoginVC ()
{
    
    int cutdown;
    NSString *invationUid;
    NSDictionary *rulesDic;
    
    BOOL loginAgreementBool;

}
@property(nonatomic,strong)NSArray *platformsarray;
@property (strong, nonatomic) UIWindow *window;
@property(nonatomic,strong)NSTimer *cutTimer;
@property (nonatomic, strong)NSString *countrycode;

@end

@implementation DspLoginVC


- (void)getP{
    
    
    UIPasteboard *p = [UIPasteboard generalPasteboard];
    
    for (NSDictionary *dict in p.items) {
        NSLog(@"Dict: %@", dict);
        NSString *plainText = [dict valueForKey:@"public.utf8-plain-text"];
        if(plainText&&[plainText containsString:@"yunbaokj-code#"]){
            NSRange codeRange = [plainText rangeOfString:@"yunbaokj-code#"];
            NSUInteger index = codeRange.location + codeRange.length;
            NSString *code = [plainText substringFromIndex:index];
            if(code&&code.length>0)
            {
                invationUid = code;
//                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"邀请码" message:code preferredStyle:UIAlertControllerStyleAlert];
//               
//                UIAlertAction *okBtn = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//                }];
//                
//                [alert addAction:okBtn];
//                [self presentViewController:alert animated:YES completion:nil];
            }
        }
    }
    
    
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBarHidden = YES;
    //指示器消失
    [PublicView indictorHide];
    
    [self getLoginThird];
    
    [[PublicObj publicInstance]addCusDelayedRemove];
    
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    //指示器消失
    [PublicView indictorHide];
    self.navigationController.navigationBarHidden = YES;
}
//获取三方登录方式
-(void)getLoginThird{
    YBWeakSelf;
    
    [WYNetworking postWithUrl:@"Home.getLogin" Dic:nil Suc:^(int code, id info, NSString *msg) {
        if (code == 0) {
            NSDictionary *infoDic = [info firstObject];
            if ([infoDic valueForKey:@"login_type_ios"]&&[[infoDic valueForKey:@"login_type_ios"] isKindOfClass:[NSArray class]]) {
                weakSelf.platformsarray = [infoDic valueForKey:@"login_type_ios"];
            }else{
                weakSelf.platformsarray = [infoDic valueForKey:@"login_type"];
            }
            rulesDic = [infoDic valueForKey:@"login_alert"];
            dispatch_async(dispatch_get_main_queue(), ^{
                [self setthirdview];
                [self showPrivateRule];
            });
        }
        //指示器消失
        [PublicView indictorHide];
    } Fail:^(id fail) {
        //指示器消失
        [PublicView indictorHide];
    }];
    
}
//添加登陆方式
-(void)setthirdview{
    //进入此方法钱，清除所有按钮，防止重复添加
    for (UIButton *btn in _platformView.subviews) {
        [btn removeFromSuperview];
    }
    //如果返回为空，登陆方式字样隐藏
    if (_platformsarray.count == 0) {
        _otherView.hidden = YES;
    }
    else{
        _otherView.hidden = NO;
    }
    //注意：此处涉及到精密计算，轻忽随意改动
    CGFloat w = 50;
    CGFloat x;
    CGFloat centerX = _window_width/2;
    if (_platformsarray.count % 2 == 0) {
        x =  centerX - _platformsarray.count/2*w - (_platformsarray.count - 1)*10;
    }
    else{
        x =  centerX - (_platformsarray.count - 1)/2*w - w/2 - (_platformsarray.count - 1)*10;
    }
    for (int i=0; i<_platformsarray.count; i++) {
        UIButton *btn = [UIButton buttonWithType:0];
        btn.tag = 1000 + i;
        [btn setImage:[UIImage imageNamed:_platformsarray[i]] forState:UIControlStateNormal];
        [btn setTitle:_platformsarray[i] forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor clearColor] forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(thirdlogin:) forControlEvents:UIControlEventTouchUpInside];
        btn.frame = CGRectMake(x,0,w,w);
        x+=w+20;
        [_platformView addSubview:btn];
    }
}
//若要添加登陆方式，在此处添加
-(void)thirdlogin:(UIButton *)sender{
    if (loginAgreementBool == NO) {
        [MBProgressHUD showError:YZMsg(@"请仔细阅读用户协议并勾选")];
        return;
    }

    /*
     1 qq
     2 wx
     3 facebook
     4 twitter
     5 ios
     */
    SSDKPlatformType logType;
    if ([sender.titleLabel.text isEqual:@"qq"]) {
        logType = SSDKPlatformTypeQQ;
    }else if ([sender.titleLabel.text isEqual:@"wx"]) {
        logType = SSDKPlatformTypeWechat;
    }else if ([sender.titleLabel.text isEqual:@"facebook"]) {
        logType = SSDKPlatformTypeFacebook;
    }else if ([sender.titleLabel.text isEqual:@"twitter"]) {
        logType = SSDKPlatformTypeTwitter;
    }else if ([sender.titleLabel.text isEqual:@"ios"]){
        logType = SSDKPlatformTypeAppleAccount;
    }else{
        logType = SSDKPlatformTypeAny;
    }
        
    [self login:sender.titleLabel.text platforms:logType];
    
}
-(void)forwardGround{
    //指示器消失
    [PublicView indictorHide];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    _topSpace.constant = statusbarHeight+25;
    
    _topTitleL.text = YZMsg(@"注册登录后体验更多精彩瞬间");
    _phoneTF.placeholder = YZMsg(@"请输入手机号码");
    _codeTF.placeholder = YZMsg(@"请输入验证码");
    [_codeBtn setTitle:YZMsg(@"获取验证码") forState:UIControlStateNormal];
    [_loginBtn setTitle:YZMsg(@"立即登录") forState:0];
    
    _midTitleL.text = YZMsg(@"其他登录方式");
    _codeDesL.text = YZMsg(@"*短信验证保障账户安全的同时短信费用将由平台支付");
    self.countrycode = @"86";

    self.naviView.hidden = YES;
    _phoneTF.placeCol = RGB_COLOR(@"#646464", 1);
    _codeTF.placeCol = RGB_COLOR(@"#646464", 1);
    invationUid = @"";
    cutdown = 60;
    self.platformsarray = [NSArray array];
    //[self getP];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(forwardGround) name:UIApplicationWillEnterForegroundNotification object:nil];
    AFNetworkReachabilityManager *netManager = [AFNetworkReachabilityManager sharedManager];
    [netManager startMonitoring];  //开始监听 防止第一次安装不显示
    [netManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status){
        if (status == AFNetworkReachabilityStatusNotReachable)
        {
            [self getLoginThird];
            return;
        }else if (status == AFNetworkReachabilityStatusUnknown || status == AFNetworkReachabilityStatusNotReachable){
            NSLog(@"nonetwork-------");
            [self getLoginThird];
        }else if ((status == AFNetworkReachabilityStatusReachableViaWWAN)||(status == AFNetworkReachabilityStatusReachableViaWiFi)){
            [self getLoginThird];
            NSLog(@"wifi-------");
        }
    }];
    self.navigationController.interactivePopGestureRecognizer.delegate = (id) self;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(ChangeBtnBackground) name:UITextFieldTextDidChangeNotification object:nil];
    
    [_xyBtn setImage:[UIImage imageNamed:@"xieyi_sel"] forState:UIControlStateSelected];
    [_xyBtn setImage:[UIImage imageNamed:@"xieyi"] forState:UIControlStateNormal];
}
-(void)login:(NSString *)types platforms:(SSDKPlatformType)platform{
    //指示器显示
    [PublicView indictorShow];
    [ShareSDK cancelAuthorize:platform result:nil];
    [ShareSDK getUserInfo:platform
           onStateChanged:^(SSDKResponseState state, SSDKUser *user, NSError *error)     {
        //指示器消失
        [PublicView indictorHide];
         if (state == SSDKResponseStateSuccess) {

             NSLog(@"uid=%@",user.uid);
             NSLog(@"%@",user.credential);
             NSLog(@"token=%@",user.credential.token);
             NSLog(@"nickname=%@",user.nickname);
             [self RequestLogin:user LoginType:types];

         } else if (state == 2 || state == 3) {
             
             if ([types isEqual:@"ios"] && [PublicObj getSysVersion] < 13) {
                 [MBProgressHUD showPop:YZMsg(@"ios13以下系统暂不支持苹果登录")];
             }
         }
     }];

}
-(void)ChangeBtnBackground {
    
   
}

-(void)RequestLogin:(SSDKUser *)user LoginType:(NSString *)LoginType
{
    NSString *icon = nil;
    if ([LoginType isEqualToString:@"qq"]) {
        icon = [user.rawData valueForKey:@"figureurl_qq_2"];
    } else {
        icon = user.icon;
    }
    if (!icon) {
        icon = @"";
    }
    NSString *userName = minstr(user.nickname);
    if ([PublicObj checkNull:userName]) {
        userName = @"";
    }
    NSString *unionid = user.uid;
    if ([LoginType isEqual:@"wx"]) {
        unionid = [user.rawData valueForKey:@"unionid"];
    }
    NSString *accessToken = user.credential.token;
    /* 改为接口传递pushid
    NSString *pushid;
    if ([JPUSHService registrationID]) {
        pushid = [JPUSHService registrationID];
    }else{
        pushid = @"";
    }
    */
    NSDictionary *dic =@{
                         @"openid":[self encodeString:unionid],
                         @"type":[self encodeString:LoginType],
                         @"nicename":[self encodeString:userName],
                         @"avatar":[self encodeString:icon],
                         @"source":@"ios",
                         @"mobileid":[PublicObj getDeviceUUID],
                         @"access_token":accessToken,
                         //@"pushid":pushid,
                         };
    YBWeakSelf;
    [WYNetworking postWithUrl:@"Login.userLoginByThird" Dic:dic Suc:^(int code, id info, NSString *msg) {
        if(code == 0) {
            NSDictionary *infoDic = [info firstObject];
            [Config saveUnified:infoDic];
            [self LoginJM];
            /*
            NSString *aliasStr = [NSString stringWithFormat:@"%@PUSH",[Config getOwnID]];
            [JPUSHService setAlias:aliasStr callbackSelector:nil object:nil];
             */
            //判断第一次登陆
            NSString *isreg = minstr([infoDic valueForKey:@"isreg"]);
            [Config saveisreg:isreg];
            [Config saveFirstBonus:@"1"];
            [weakSelf login];
        }else{
            [MBProgressHUD showError:msg];
        }
        //指示器消失
        [PublicView indictorHide];
    } Fail:^(id fail) {
        [MBProgressHUD showError:YZMsg(@"请重试")];
        //指示器消失
        [PublicView indictorHide];
    }];
   
}
-(NSString*)encodeString:(NSString*)unencodedString{
    NSString*encodedString=(NSString*)
    CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                              (CFStringRef)unencodedString,
                                                              NULL,
                                                              (CFStringRef)@"!*'();:@&=+$,/?%#[]",
                                                              kCFStringEncodingUTF8));
    return encodedString;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
   
}



- (IBAction)clickCountryBtn:(UIButton *)sender {
    
    YBWeakSelf;
    CountryCodeVC *codeVC = [[CountryCodeVC alloc]init];
    codeVC.codeEvent = ^(NSDictionary *codeDic) {
        NSString *codeStr = [NSString stringWithFormat:@"+%@",minstr([codeDic valueForKey:@"tel"])];
        [weakSelf.countryBtn setTitle:codeStr forState:0];
        weakSelf.countrycode = minstr([codeDic valueForKey:@"tel"]);
    };
    [[YBBaseAppDelegate sharedAppDelegate] pushViewController:codeVC animated:YES];
    
}
//- (IBAction)clickPrivateBtn:(UIButton *)sender {
//    PubH5 *VC = [[PubH5 alloc]init];
//    NSString *paths = [h5url stringByAppendingString:@"/portal/page/index?id=26"];
//    VC.url = paths;
//    [self.navigationController pushViewController:VC animated:YES];
//}

- (IBAction)clickGetCodeBtn:(UIButton *)sender {
    
    cutdown = 60;
    /* 都改为服务端判断
    if (_phoneTF.text.length == 0) {
        [MBProgressHUD showPop:YZMsg(@"请填写手机号")];
        return;
    }
    if (_phoneTF.text.length !=11) {
        [MBProgressHUD showPop:YZMsg(@"手机号输入错误")];
        return;
    }*/
    
    [_codeTF becomeFirstResponder];
    sender.userInteractionEnabled = NO;
    YBWeakSelf;
//    NSString *postUrl = [NSString stringWithFormat:@"Login.getLoginCode&mobile=%@",_phoneTF.text];
   
    NSDictionary *signdic = @{@"mobile":_phoneTF.text,@"time":[NSNumber numberWithLong: (long)[[NSDate date] timeIntervalSince1970]]};
    NSString *sign = [PublicObj sortString:signdic];

    NSDictionary *parDic = @{@"country_code":self.countrycode,
                             @"mobile":_phoneTF.text,
                             @"time":[NSNumber numberWithLong: (long)[[NSDate date] timeIntervalSince1970]],
                             @"sign":sign
    };
    [WYNetworking postWithUrl:@"Login.getLoginCode" Dic:parDic Suc:^(int code, id info, NSString *msg) {
        if (code == 0) {
            sender.userInteractionEnabled = YES;
            if (!weakSelf.cutTimer) {
                weakSelf.cutTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(doCutTimer) userInfo:nil repeats:YES];
            }
            [MBProgressHUD showPop:YZMsg(@"发送成功")];
        }else{
            sender.userInteractionEnabled = YES;
            [MBProgressHUD showPop:msg];
        }
        sender.userInteractionEnabled = YES;
    } Fail:^(id fail) {
        sender.userInteractionEnabled = YES;
    }];
    
}

-(void)doCutTimer {
    [_codeBtn setTitle:[NSString stringWithFormat:@"%ds",cutdown] forState:UIControlStateNormal];
    [_codeBtn setTitleColor:RGB_COLOR(@"#646464", 1) forState:0];
    
    _codeBtn.userInteractionEnabled = NO;
    if (cutdown<=0) {
        [_codeBtn setTitle:YZMsg(@"获取验证码") forState:UIControlStateNormal];
        [_codeBtn setTitleColor:RGB_COLOR(@"#B4B4B4", 1) forState:0];
        _codeBtn.userInteractionEnabled = YES;
        [_cutTimer invalidate];
        _cutTimer = nil;
        cutdown = 60;
    }
    cutdown-=1;
}

- (IBAction)clickPhoneLogin:(UIButton *)sender {
    
    if (loginAgreementBool == NO) {
        [MBProgressHUD showError:YZMsg(@"请仔细阅读用户协议并勾选")];
        return;
    }

    [self.view endEditing:YES];
    //指示器显示
    [PublicView indictorShow];
    /* 改为接口传递pushid
    NSString *pushid;
    if ([JPUSHService registrationID]) {
        pushid = [JPUSHService registrationID];
    }else{
        pushid = @"";
    }
    */
    NSDictionary *Login = @{
                            @"user_login":_phoneTF.text,
                            @"code":_codeTF.text,
                            @"source":@"ios",
                            @"mobileid":[PublicObj getDeviceUUID],
                            @"country_code":self.countrycode
                            //@"pushid":pushid,
                            };
    YBWeakSelf;
    [WYNetworking postWithUrl:@"Login.userLogin" Dic:Login Suc:^(int code, id info, NSString *msg) {
       
        if(code == 0) {
            NSDictionary *infoDic = [info objectAtIndex:0];
            [Config saveUnified:infoDic];
            /*
            NSString *aliasStr = [NSString stringWithFormat:@"%@PUSH",[Config getOwnID]];
            [JPUSHService setAlias:aliasStr callbackSelector:nil object:nil];
             */
            [self LoginJM];
            //判断第一次登陆
            NSString *isreg = minstr([infoDic valueForKey:@"isreg"]);
            [Config saveisreg:isreg];
            [Config saveFirstBonus:@"1"];

            [weakSelf login];
        }else {
            [MBProgressHUD showPop:msg];
        }
        //指示器消失
        [PublicView indictorHide];
    } Fail:^(id fail) {
        //指示器消失
        [PublicView indictorHide];
    }];
    
}

- (IBAction)clickBackBtn:(UIButton *)sender {
    
    if ([_youke isEqualToString:@"不是游客"]) {
        
        [Config saveUnified:[PublicObj visitorDic]];
        YBTabBarController *root = [[YBTabBarController alloc]initWithAlert:NO];
        YBNavigationController *navroot = [[YBNavigationController alloc]initWithRootViewController:root];
        UIApplication *app =[UIApplication sharedApplication];
        AppDelegate *app2 = (AppDelegate *)app.delegate;
        [app2.window removeAllSubViews];
        app2.window.rootViewController = navroot;
        
    }else{
        if (_isOverdue) {
            [PublicObj resetVC:[[YBTabBarController alloc]initWithAlert:NO]];
        }else{
            [self dismissViewControllerAnimated:YES completion:nil];
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
}

-(void)LoginJM{
    [[YBImManager shareInstance] imLogin];
}

-(void)login{
    [[NSNotificationCenter defaultCenter]postNotificationName:@"showHomeVideoRed" object:nil];
    AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
    [PublicObj updatePushId:app.jgRegistrationID];
//    //进入全功能模式
//    [Config saveTranslate:YES];
//
//    [[NSNotificationCenter defaultCenter]postNotificationName:@"hideBottomFunBtn" object:nil];
    [YBInviteCode checkAgent];
    [Config saveSignOfDelVideo:@"1"];
    // 需要弹青少年提示
    [YBYoungManager shareInstance].needShowPop = YES;
    [[YBBaseAppDelegate sharedAppDelegate] popViewController:NO];
    /*
    YBTabBarController *root = [[YBTabBarController alloc]initWithAlert:YES];
    
    //[self.navigationController pushViewController:root animated:YES];
    
    UIApplication *app =[UIApplication sharedApplication];
    AppDelegate *app2 = (AppDelegate*)app.delegate;
    UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:root];
    [app2.window removeAllSubViews];
    app2.window.rootViewController = nav;
    */
}
//键盘的隐藏
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

-(void)showAler:(int)code {
    if (code == -1) {
        [[YBBaseAppDelegate sharedAppDelegate]popViewController:YES];
    }
}
-(void)showPrivateRule {
    
    //弹窗 === 改为 YBPrivateVC 显示 又改回来了【20-7-3】
    YBWeakSelf;
    if (_showAlert) {
        _showAlert = NO;
        [RegAlertView showRegAler:rulesDic complete:^(int code) {
            [weakSelf showAler:code];
        }];
    }
    
    _privateL.hidden = NO;
    _privateL.text = minstr([rulesDic valueForKey:@"login_title"]);//@"登录即代表你同意";
    _privateL.textColor = RGB_COLOR(@"#323232", 1);
    _privateL.font = SYS_Font(15);
    _privateL.numberOfLines = 0;
    
    NSArray *ppA = [NSArray arrayWithArray:[rulesDic valueForKey:@"message"]];
    
//    for (int i=0; i<ppA.count; i++) {
//        NSDictionary *subDic = ppA[i];
//        if (i==0) {
//            _privateL.text = [NSString stringWithFormat:@"%@%@",_privateL.text,[subDic valueForKey:@"title"]];
//        }else{
//            _privateL.text = [NSString stringWithFormat:@"%@和%@",_privateL.text,[subDic valueForKey:@"title"]];
//        }
//    }
    
    NSMutableAttributedString *textAtt = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"%@",_privateL.text]];
    [textAtt addAttribute:NSForegroundColorAttributeName value:RGB_COLOR(@"#6F6F6F", 1) range:textAtt.yy_rangeOfAll];
    
    for (int i=0; i<ppA.count; i++) {
        NSDictionary *subDic = ppA[i];
        NSRange clickRange = [[textAtt string]rangeOfString:minstr([subDic valueForKey:@"title"])];
        //RGB_COLOR(@"#5C94E7", 1)
        [textAtt yy_setTextHighlightRange:clickRange color:Pink_Cor backgroundColor:[UIColor clearColor] tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
            NSLog(@"协议");
            if ([PublicObj checkNull:minstr([subDic valueForKey:@"url"])]) {
                [MBProgressHUD showError:YZMsg(@"链接不存在")];
                return;
            }
            PubH5 *h5vc = [[PubH5 alloc]init];
            h5vc.url = minstr([subDic valueForKey:@"url"]);;
            [[YBBaseAppDelegate sharedAppDelegate]pushViewController:h5vc animated:YES];
        }];
    }
    textAtt.yy_alignment = NSTextAlignmentCenter;
    _privateL.attributedText = textAtt;
    
//    CGFloat widthss = [PublicObj widthOfString:minstr([rulesDic valueForKey:@"login_title"]) andFont:[UIFont systemFontOfSize:14] andHeight:30];
    [_xyBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(_privateL.mas_left).offset(-5);
        make.centerY.equalTo(_privateL.mas_centerY);
        make.height.width.mas_equalTo(12);
        }];

}
- (IBAction)protolBtnClick:(UIButton *)sender {
    loginAgreementBool = !loginAgreementBool;
    if (loginAgreementBool) {
        _xyBtn.selected = YES;
    }else{
        _xyBtn.selected = NO;
    }

}

@end
